﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using ProxyTool.Models;
using ProxyTool.Setting;
using ProxyTool.Utils;

namespace ProxyTool.Forms
{
    public partial class SettingForm : Form
    {
        public SettingForm()
        {
            InitializeComponent();
            txtName.Text = SettingManagement.Instance.Setting.Name;
            txtU9URI.Text = SettingManagement.Instance.Setting.U9URI;
            txtEnterpriseID.Text = SettingManagement.Instance.Setting.EnterpriseID;
            txtOrgCode.Text = SettingManagement.Instance.Setting.OrgCode;
            txtUserCode.Text = SettingManagement.Instance.Setting.UserCode;
            txtPassword.Text = string.IsNullOrEmpty(SettingManagement.Instance.Setting.Password)
                ? "      "
                : SettingManagement.Instance.Setting.Password;
            txtCulture.Text = SettingManagement.Instance.Setting.Culture;
            txtSupportCultureNameList.Text = SettingManagement.Instance.Setting.SupportCultureNameList;
            txtDefaultRequestDataMaxExpandDepth.Text =
                SettingManagement.Instance.Setting.DefaultRequestDataMaxExpandDepth.ToString();
            chkDefaultUseDataContract.Checked =
                SettingManagement.Instance.Setting.DefaultUseDataContract;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                int defaultRequestDataMaxExpandDepth;
                if (string.IsNullOrWhiteSpace(txtDefaultRequestDataMaxExpandDepth.Text))
                {
                    txtDefaultRequestDataMaxExpandDepth.Focus();
                    throw new ProxyToolException("默认请求数据最大展开深度不能为空");
                }

                var isOk = int.TryParse(txtDefaultRequestDataMaxExpandDepth.Text, out defaultRequestDataMaxExpandDepth);
                if (!isOk || defaultRequestDataMaxExpandDepth <= 0)
                    throw new ProxyToolException("默认请求数据最大展开深度必须为数字且大于0");
                //停止所有的调试
                SettingManagement.Instance.StopAllDebug();
                SettingManagement.Instance.Setting.Name = txtName.Text;
                SettingManagement.Instance.Setting.EnterpriseID = txtEnterpriseID.Text;
                SettingManagement.Instance.Setting.OrgCode = txtOrgCode.Text;
                SettingManagement.Instance.Setting.UserCode = txtUserCode.Text;
                SettingManagement.Instance.Setting.Password = txtPassword.Text.Trim();
                SettingManagement.Instance.Setting.Culture = txtCulture.Text;
                SettingManagement.Instance.Setting.SupportCultureNameList = txtSupportCultureNameList.Text;
                SettingManagement.Instance.Setting.U9URI = txtU9URI.Text;
                SettingManagement.Instance.Setting.DefaultRequestDataMaxExpandDepth = defaultRequestDataMaxExpandDepth;
                SettingManagement.Instance.Setting.DefaultUseDataContract =
                    chkDefaultUseDataContract.Checked;
                SettingManagement.Instance.SaveSetting();
                //初始化调试
                SettingManagement.Instance.InitDebug();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "设置异常");
                DialogResult = DialogResult.None;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (DialogResult == DialogResult.None)
                e.Cancel = true;
            base.OnClosing(e);
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            var contextManagerForm = new ContextDataManagerForm();
            if (contextManagerForm.ShowDialog() == DialogResult.OK)
            {
                ContextData contextData = contextManagerForm.GetReturnContextData();
                if (contextData == null) return;
                //设置值通过上下文数据
                SetValueFromContextData(contextData);
            }
        }

        /// <summary>
        ///     设置值通过上下文数据
        /// </summary>
        /// <param name="contextData"></param>
        private void SetValueFromContextData(ContextData contextData)
        {
            txtName.Text = contextData.Name;
            txtU9URI.Text = contextData.U9URI;
            txtEnterpriseID.Text = contextData.Enterprise == null ? string.Empty : contextData.Enterprise.Code;
            txtOrgCode.Text = contextData.Org == null ? string.Empty : contextData.Org.Code;
            txtUserCode.Text = contextData.UserCode;
            txtPassword.Text = contextData.Password;
            txtCulture.Text = contextData.Language == null ? string.Empty : contextData.Language.Code;
            List<string> supportCultureNameList = new List<string>();
            if (contextData.Languages != null)
            {
                foreach (LanguageData languageData in contextData.Languages)
                {
                    supportCultureNameList.Add(languageData.Code);
                }
            }

            txtSupportCultureNameList.Text = supportCultureNameList.Count > 0
                ? string.Join(",", supportCultureNameList)
                : txtCulture.Text;
        }

        private void btnSelect_MouseHover(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            if (btn == null) return;
            btn.FlatAppearance.BorderSize = 1;
        }

        private void btnSelect_MouseLeave(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            if (btn == null) return;
            btn.FlatAppearance.BorderSize = 0;
        }

        private void selectContextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            selectContextMenuStrip.Items.Clear();
            if (SettingManagement.Instance.ContextDatas == null ||
                SettingManagement.Instance.ContextDatas.Count == 0)
            {
                e.Cancel = true;
                return;
            }

            foreach (ContextData contextData in SettingManagement.Instance.ContextDatas)
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Text = ContextDataManagerForm.GetContextDataListItemText(contextData);
                item.Tag = contextData;
                selectContextMenuStrip.Items.Add(item);
            }
        }

        /// <summary>
        ///     选择菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void selectContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            ContextData contextData = e.ClickedItem.Tag as ContextData;
            if (contextData == null) return;
            //设置值通过上下文数据
            SetValueFromContextData(contextData);
        }

    }
}